package com.bos.service;

import com.bos.data.model.BosUserModel;
import com.bos.test.UserTest;
import com.bos.util.QiWeiXinParamesUtil;
import com.bos.util.WeiXinUtil;
import com.google.gson.Gson;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Contacts_UserService {
    private static Logger log = LoggerFactory.getLogger(UserTest.class);

    private String createUser_url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=ACCESS_TOKEN";
    private String getUser_url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID";
    private String updateUser_url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=ACCESS_TOKEN";
    private String deleteUser_url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=USERID";
    private String batchdeleteUser_url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=ACCESS_TOKEN";
    private String getDepartmentUser_url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD";
    private String getDepartmentUserDetails_url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD";
    private String getUser_url2 = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&agentid=AGENTID&code=CODE";

    //将静态变量传给另外一个java类
    public static String USERNAME;//名字
    public static String AVATARS;//头像
    //1.创建成员
    public void createUser(String accessToken, BosUserModel user) {

        //1.获取json字符串：将user对象转换为json字符串
        Gson gson = new Gson();
        String jsonU1 = gson.toJson(user);      //使用gson.toJson(user)即可将user对象顺序转成json
        System.out.println("jsonU1:" + jsonU1);


        //2.获取请求的url
        createUser_url = createUser_url.replace("ACCESS_TOKEN", accessToken);

        //3.调用接口，发送请求，创建成员
        JSONObject jsonObject = WeiXinUtil.httpRequest(createUser_url, "POST", jsonU1);
        System.out.println("jsonObject:" + jsonObject.toString());

        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("创建成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }

    //2.获取成员
    public void getUser(String userId, String accessToken) {
        System.out.println(getUser_url);
        //1.获取请求的url
        getUser_url = getUser_url.replace("ACCESS_TOKEN", accessToken)
                .replace("USERID", userId);
        System.out.println(getUser_url);
        //2.调用接口，发送请求，获取成员
        JSONObject jsonObject = WeiXinUtil.httpRequest(getUser_url, "GET", null);
        System.out.println("jsonObject:" + jsonObject.toString());
        //得到username将其保存到session中
        String name = jsonObject.get("name").toString();
        Contacts_UserService.USERNAME = name;
        String avatar = jsonObject.get("avatar").toString();
        Contacts_UserService.AVATARS = avatar;
        //3.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("获取成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }

    //2.获取成员
    public void getUser2(String code, String accessToken) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accessToken + "&agentid=" + QiWeiXinParamesUtil.agentId + "&code=" + code;
        //1.获取请求的url
        getUser_url2 = getUser_url2.replace("ACCESS_TOKEN", accessToken)
                .replace("CODE", code).replace("AGENTID", QiWeiXinParamesUtil.agentId + "");
        //2.调用接口，发送请求，获取成员
        JSONObject jsonObject = WeiXinUtil.httpRequest(getUser_url2, "GET", null);

        //3.错误消息处理
        if (null != jsonObject) {
            System.out.println("jsonObject:" + jsonObject.toString());
            //jsonObject:{"UserId":"d41d8cd98f00b204e9800998ecf8427e","DeviceId":"","errcode":0,"errmsg":"ok"}
            //接下来将userid 和accessToken获取用户信息
        	/*  String userId=jsonObject.get("UserId").toString();

        	  N=userId;*/

            getUser(jsonObject.get("UserId").toString(), accessToken);
            //此时这个时候应该把值给传到ResfILTER中
            if (0 != jsonObject.getInt("errcode")) {
                log.error("获取成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }

    //3.更新成员
    public void updateUser(String accessToken, BosUserModel user) {

        //1.获取json字符串：将user对象转换为json字符串
        Gson gson = new Gson();
        String jsonU1 = gson.toJson(user);      //使用gson.toJson(user)即可将user对象顺序转成json
        System.out.println("jsonU1:" + jsonU1);


        //2.获取请求的url
        updateUser_url = updateUser_url.replace("ACCESS_TOKEN", accessToken);

        //3.调用接口，发送请求，创建成员
        JSONObject jsonObject = WeiXinUtil.httpRequest(updateUser_url, "POST", jsonU1);
        System.out.println("jsonObject:" + jsonObject.toString());

        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("更新成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }

    //4.删除成员
    public void deleteUser(String accessToken, String userId) {

        //1.获取请求的url
        deleteUser_url = deleteUser_url.replace("ACCESS_TOKEN", accessToken)
                .replace("USERID", userId);

        //2.调用接口，发送请求，删除成员
        JSONObject jsonObject = WeiXinUtil.httpRequest(deleteUser_url, "GET", null);
        System.out.println("jsonObject:" + jsonObject.toString());

        //3.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("删除成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }

    //5.批量删除成员
    public void batchdeleteUser(String accessToken, List<String> userIdList) {
        //1.获取json字符串：将user对象转换为json字符串
        Map<String, Object> content = new HashMap<String, Object>();
        content.put("useridlist", userIdList);

        Gson gson = new Gson();
        String useridlist = gson.toJson(content);
        System.out.println(useridlist);

        //2.获取请求的url
        batchdeleteUser_url = batchdeleteUser_url.replace("ACCESS_TOKEN", accessToken);

        //3.调用接口，发送请求，创建成员
        JSONObject jsonObject = WeiXinUtil.httpRequest(batchdeleteUser_url, "POST", useridlist);
        System.out.println("jsonObject:" + jsonObject.toString());

        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("批量删除成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }


    //6.获取部门成员
    public void getDepartmentUser(String accessToken, String departmentId, String fetchChild) {

        //1.获取请求的url
        getDepartmentUser_url = getDepartmentUser_url.replace("ACCESS_TOKEN", accessToken)
                .replace("DEPARTMENT_ID", departmentId)
                .replace("FETCH_CHILD", fetchChild);

        //2.调用接口，发送请求，获取部门成员
        JSONObject jsonObject = WeiXinUtil.httpRequest(getDepartmentUser_url, "GET", null);
        System.out.println("jsonObject:" + jsonObject.toString());

        //3.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("获取部门成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }


    //7.获取部门成员详情
    public List<BosUserModel> getDepartmentUserDetails(List<String> depts, String accessToken, String fetchChild) {
        List<BosUserModel> users = new ArrayList<BosUserModel>();
        for(int j=0;j<depts.size();j++){
            // for (String deptId : depts) {
            // 1.获取请求的url
            String str= getDepartmentUserDetails_url
                    .replace("ACCESS_TOKEN", accessToken)
                    .replace("DEPARTMENT_ID",depts.get(j))
                    .replace("FETCH_CHILD", fetchChild);

            // 2.调用接口，发送请求，获取部门成员
            JSONObject jsonObject = WeiXinUtil.httpRequest(str, "GET", null);
            System.out.println("Contact_service----jsonObject:" + jsonObject.toString());

            // 3.错误消息处理
            if (null != jsonObject) {
                if (0 != jsonObject.getInt("errcode")) {
                    log.error("获取部门成员详情失败 errcode:{} errmsg:{}",
                            jsonObject.getInt("errcode"),
                            jsonObject.getString("errmsg"));
                } else {//查询成功的话
                    JSONArray array = jsonObject.getJSONArray("userlist");
                    if (null != array) {
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject de = JSONObject.fromObject(array.get(i));
                            String userid = de.get("userid").toString();
                            String department = de.get("department").toString();
                            String name = de.get("name").toString();
                            String position = de.get("position").toString();
                            String mobile = de.get("mobile").toString();
                            String gender = de.get("gender").toString();
                            String email = de.get("email").toString();
                            String avatar=de.get("avatar").toString();
                            //先将名字等信息传过去
                            BosUserModel user = new BosUserModel();
                            user.setUserId(userid);
                            user.setDepartment(department);
                            user.setName(name);
                            user.setPosition(position);
                            user.setMobile(mobile);
                            user.setGender(gender);
                            user.setEmail(email);
                            user.setAvatar(avatar);//头像
                            //最后将user放到list中去
                            users.add(user);
                        }

                    }

                }
            }
        }
        return users;
    }
}
 